// pages/film-CD-up/film-CD-up.js
const app = getApp();
const db = wx.cloud.database().collection("venue");
const chooseLocation = requirePlugin('chooseLocation');

Page({
  data: {
    venue: '',
    location: '',
    contact: '',
    rent: '',
    address: '',
    locationName: '',
    latitude: '', // 维度
    longitude: '', // 经度
    originFiles: [],
    uploadedImgUrls: [], // Array to store uploaded image URLs
    gridConfig: {
      column: 4,
      width: 160,
      height: 160,
    },
  },

  handleSuccess(e) {
    const { files } = e.detail;
    this.setData({
      originFiles: files
    });
  },

  handleRemove(e) {
    const { index } = e.detail;
    const { originFiles } = this.data;
    originFiles.splice(index, 1);
    this.setData({
      originFiles
    });
  },

  handleClick(e) {
    console.log(e.detail.file);
  },

  handleDrop(e) {
    const { files } = e.detail;
    this.setData({
      originFiles: files
    });
  },

  onShow: function () {
    const location = chooseLocation.getLocation();
    if (location) {
      this.setData({
        address: location.address || '',
        locationName: location.name || '',
        location: location.address,
        latitude: location.latitude,
        longitude: location.longitude
      });
    }
  },

  showMap() {
    const key = "564BZ-N5WC5-LBFIZ-ISK6L-N3C2O-WJBSQ"; // 腾讯位置服务的key
    const referer = "wx6b09b29f03c63446"; // 调用插件的app的名称
    wx.navigateTo({
      url: 'plugin://chooseLocation/index?key=' + key + '&referer=' + referer
    });
  },

  uploadImages(tempImgUrls) {
    return Promise.all(tempImgUrls.map(tempImgUrl => {
      return wx.cloud.uploadFile({
        cloudPath: 'venue/' + (new Date()).valueOf() + '.png',
        filePath: tempImgUrl,
      }).then(res => ({
        url: res.fileID
      }));
    }));
  },

  publishRent() {
    const { venue, location, contact, rent, originFiles, latitude, longitude } = this.data;

    if (!venue || !location || !contact || !rent) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'error'
      });
      return;
    }

    if (originFiles.length > 0) {
      wx.showLoading({
        title: '图片上传中',
      });

      const tempImgUrls = originFiles.map(file => file.url);
      this.uploadImages(tempImgUrls).then(imgUrls => {
        this.setData({ uploadedImgUrls: imgUrls });
        this.addDataToDatabase();
      }).catch(err => {
        console.error('Upload failed', err);
        wx.showToast({
          title: '上传失败，请重试',
          icon: 'none'
        });
      }).finally(() => {
        wx.hideLoading();
      });
    } else {
      this.addDataToDatabase();
    }
  },

  addDataToDatabase() {
    const { venue, location, contact, rent, uploadedImgUrls, latitude, longitude } = this.data;

    db.add({
      data: {
        venue: venue,
        location: location,
        contact: contact,
        rent: rent,
        venue_urls: uploadedImgUrls,
        location2: [longitude, latitude]
      }
    }).then(res => {
      console.log('Data added successfully', res);
      this.setData({
        venue: '',
        location: '',
        contact: '',
        rent: '',
        uploadedImgUrls: [],
        latitude: '',
        longitude: '',
        address: '',
        locationName: '',
        originFiles: []
      });
      wx.showToast({
        title: '提交成功',
        icon: 'success'
      });
    }).catch(err => {
      console.error('Data addition failed', err);
      wx.showToast({
        title: '提交失败，请重试',
        icon: 'none'
      });
    }).finally(() => {
      wx.hideLoading();
    });
  },

  onUnload: function () {
    const pages = getCurrentPages();
    if (pages.length >= 2) {
      const prevPage = pages[pages.length - 2];
      if (prevPage.getEquipmentData) {
        prevPage.getEquipmentData();
      }
    }
    chooseLocation.setLocation(null);
  }
});
